package com.example.exceldemo.liteflowComponent.qh;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.highlight.HighlightRenderData;
import com.deepoove.poi.plugin.highlight.HighlightRenderPolicy;
import com.deepoove.poi.plugin.highlight.HighlightStyle;
import com.example.exceldemo.constants.ReqMgrConstants;
import com.example.exceldemo.liteflowComponent.common.GenerateDocuments;
import com.example.exceldemo.model.*;
import com.example.exceldemo.util.WordUtil;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 生成需求测试文档 青海
 *
 * @author yangwb8
 * @Date 2025/5/17 04:06
 */
@LiteflowComponent("qh_two")
@Slf4j
public class GenerateQhTwoDocuments extends GenerateDocuments {

    private String sonarImagePath;
    @Override
    public void processReqDocuments(ReqInfoDTO reqInfo, String templateDir, String reqOutputDir, Map<String, String> settings) {
        log.info("开始生成需求开发自测报告");

        ClassPathResource resource = new ClassPathResource(templateDir + "/sonarDefault.png");
        sonarImagePath = resource.getPath();
        // 复制基本属性到自测报告对象
        ReqDevSelfTestReportDTO reqDevSelfTestReportDTO = prepareReqAnalysisData(reqInfo);

        // 将DTO对象转换为Map（POI-TL模板引擎需要Map格式数据）
        Map<String, Object> data = BeanUtil.beanToMap(reqDevSelfTestReportDTO);

        // 创建自测报告专用配置（添加代码高亮渲染策略）
        Configure config = Configure.builder()
                .bind("functionList", getPolicy())
                .bind("terms", getPolicy())
                .bind("testCases", getPolicy())
                .bind("scriptList", new HighlightRenderPolicy())
                .build();

        // 构建输出文件路径
        Path outputPath = Paths.get(reqOutputDir,
                getDocName(reqInfo));


        // 修改：直接使用模板文件名，无需构建完整路径
        String templateFileName = ReqMgrConstants.TEMPLATE_SELF_TEST;
        String provCode = reqInfo.getProvCode();
        // 统一使用类路径方式生成文档
        WordUtil.generateWordFileByOS(provCode,templateFileName, outputPath.toString(), data, config);
        log.info("需求开发自测报告 生成成功: {}", outputPath.toString());
    }

    private ReqDevSelfTestReportDTO prepareReqAnalysisData(ReqInfoDTO reqInfo) {
        DemoContext deoContext = getDemoContext();

        ReqDevSelfTestReportDTO reqDevSelfTestReportDTO = BeanUtil.copyProperties(deoContext.getReqAnalysisDTO(), ReqDevSelfTestReportDTO.class);
        // 生成测试用例
        List<TestCaceDTO> testCaseList = generateTestCases(deoContext.getReqAnalysisDTO(), reqInfo);
        reqDevSelfTestReportDTO.setRisk(reqInfo.getRisk());
        reqDevSelfTestReportDTO.setTestCases(testCaseList);

        reqDevSelfTestReportDTO.setCodeList("代码分支");
        reqDevSelfTestReportDTO.setScript("脚本列表");
        reqDevSelfTestReportDTO.setSonarPicBase64Str(Pictures.ofLocal(sonarImagePath).size(100, 120).create());
        reqDevSelfTestReportDTO.setModifyFileCount(String.valueOf(RandomUtil.randomInt(1, 10)));
        reqDevSelfTestReportDTO.setAddFileCount(String.valueOf(RandomUtil.randomInt(1, 10)));

        HighlightRenderData code = new HighlightRenderData();
        code.setCode(reqDevSelfTestReportDTO.getScript());
        code.setLanguage("sql");
        code.setStyle(HighlightStyle.builder().withShowLine(false).withTheme("zenburn").build());

        return reqDevSelfTestReportDTO;
    }

    @Override
    public String getDocName(ReqInfoDTO reqInfo) {
        return "青海-BSS-" + DateUtil.format(LocalDateTime.now(), "yyyyMM") + "-" + reqInfo.getReqNo() + "-"
                + reqInfo.getReqName()+"_需求开发自测报告.docx";
    }

    /**
     * 根据功能列表生成测试用例
     *
     * @param reqAnalysisDTO 需求分析数据
     * @return 测试用例列表
     */
    private  List<TestCaceDTO> generateTestCases(ReqAnalysisSpecificationDTO reqAnalysisDTO, ReqInfoDTO reqInfo) {
        List<TestCaceDTO> testCaseList = new ArrayList<>();

        reqAnalysisDTO.getFunctionList().forEach(functionInfoVO -> {
            TestCaceDTO testCaceDTO = new TestCaceDTO();
            testCaceDTO.setCaseId(RandomUtil.randomLong());
            testCaceDTO.setCaseType("功能测试-" + functionInfoVO.getName());
            testCaceDTO.setCaseName("" + functionInfoVO.getName());
            testCaceDTO.setCaseLevel("1");
            testCaceDTO.setDescription("" + functionInfoVO.getName());
            testCaceDTO.setExpectedResult("正常");
            testCaceDTO.setInParam("入参-" + functionInfoVO.getName());
            testCaceDTO.setOutParam("出参-" + functionInfoVO.getName());
            testCaceDTO.setStatus("通过");
            testCaceDTO.setCaseOwner(reqInfo.getReqDeveloper());
            testCaceDTO.setCasePics(Arrays.asList(Pictures.ofLocal(sonarImagePath).size(100, 120).create()));
            testCaceDTO.setCaseNo(reqInfo.getReqNo() + "-TEST-" + RandomUtil.randomString(3));
            testCaseList.add(testCaceDTO);
        });

        return testCaseList;
    }
}
